//
//  NSObject+Extansion.m
//  lTTheOne
//
//  Created by AA on 2024/3/10.
//

#import "NSObject+Extansion.h"
#import <objc/runtime.h>
#import "YYKit.h"

@implementation NSObject (Extansion)

#pragma mark - 模型转字典
- (NSDictionary *)modelForDict {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];

    // 属性个数变量
    unsigned int propertyCount;
    // 获取模型属性字段
    objc_property_t *property = class_copyPropertyList([self class], &propertyCount);

    for (int index = 0; index < propertyCount; index++) {
        objc_property_t prop = property[index];
        // 属性名称
        NSString *propertyName = [NSString stringWithUTF8String:property_getName(prop)];
        // 属性值
        id propertyValue = [self valueForKey:propertyName];

        if (propertyValue == nil) {
            propertyValue = @"";
        } else {
            propertyValue = [self getObjectInternal:propertyValue];
            [dict setObject:propertyValue forKey:propertyName];
        }
    }

    if (property) {
        free(property);
    }

    return dict;
}

- (id)getObjectInternal:(id)obj {
    if ([obj isKindOfClass:[NSNull class]]) {
        return @"";
    }

    if ([obj isKindOfClass:[NSString class]] || [obj isKindOfClass:[NSNumber class]]) {
        return obj;
    }

    if ([obj isKindOfClass:[NSArray class]]) {
        NSArray *objarr = obj;
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:objarr.count];
        for (int i = 0; i < objarr.count; i++) {
            [arr setObject:[self getObjectInternal:[objarr objectAtIndex:i]] atIndexedSubscript:i];
        }
        return arr;
    }

    if ([obj isKindOfClass:[NSDictionary class]]) {
        NSDictionary *objdic = obj;
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:[objdic count]];
        for (NSString *key in objdic.allKeys) {
            [dic setObject:[self getObjectInternal:[objdic objectForKey:key]] forKey:key];
        }

        return dic;
    }
    return [self modelForDict];
}

// 数组模型
+ (NSArray *)jsonsToModelsWithJsons:(NSArray *)jsons {
    NSMutableArray *models = [NSMutableArray array];
    for (NSDictionary *json in jsons) {
        [models addObject:[[self class] modelWithJSON:json]];
    }
    return models;
}

#pragma mark - 字典转模型
+ (instancetype)initDictForModel:(NSDictionary *)dict {
    id object = [[self alloc] init];

    [object setValuesForKeysWithDictionary:dict];

    return object;
}

@end
